<script setup lang="ts">
import { getCurrentInstance, ref, reactive, watch, onBeforeMount, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { Autoplay } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/autoplay'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* ---- */
const user = reactive({
  info: '',
  // ----
  title: '',
  // ----
  share_title: proxy.$shareTitle,
  share_desc: proxy.$shareDesc,
  share_icon: proxy.$shareIcon
})
// ----
const totalCount = ref(0)
// ----
const infoSch = ref(null)
const forSearch = ref(proxy.$Store.get('forSearch') || {})
// ----
const forAdvs = ref([])
const forFreeAdvs = 7 / 1
const setTrueStyleAdvs = ref({})
const forAutoplay = {
  delay: 5000,
  disableOnInteraction: false
}
const modules = [Autoplay]
// ----
const forFree = 9 / 5
const setTrueStyle = ref({})
// ----
const moveTime = 50
let showMarquee = null
// ----
const curProv = ref(null)
let myProvince = null
const myCity = ref(null)
let myDistrict = null
let myIndex = 0
const myCityData = proxy.$City
// ----
const tSpeed = 300
let bar = null
let clientWidth = 0
let navWidth = 0
let navSwiper = null
const navText = '全部'
const areas = ref([])
// --mescroll--
let noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const sliding = ref()
const preImg = ref()
const layer = ref()
const layerBox = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// --设置微信分享--
const setWebShare = (info) => {
  const forSn = proxy.$Store.get('SN')
  const currentUrl = window.location.href.split('#')[0]
  const shareLink = (Number(currentUrl.indexOf('sn=')) === Number(-1)) ? ((Number(currentUrl.indexOf('?')) === Number(-1)) ? currentUrl + '?sn=' + forSn : currentUrl + '&sn=' + forSn) : currentUrl
  proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
    if (!obj) return
    // ----
    obj.hideMenuItem()
    obj.showMenuList(['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:favorite', 'menuItem:share:QZone'])
    // ----
    obj.share({
      title: info.title,
      desc: info.desc,
      link: shareLink,
      imgUrl: info.imgUrl
    })
  })
}
// ----
const initData = () => {
  myCityData.some((one) => {
    if (Number(one.text.indexOf(myProvince)) !== Number(-1)) {
      if (one.children) {
        one.children.some((two) => {
          if (Number(two.text.indexOf(myCity.value)) !== Number(-1)) {
            if (two.children) {
              areas.value = two.children
              if (myDistrict) {
                two.children.some((three, index) => {
                  if (Number(three.text.indexOf(myDistrict)) !== Number(-1)) myIndex = index + 1
                })
              }
            } else {
              areas.value = []
            }
          }
        })
      }
    }
  })
}
// --initSwiperData || changeSwiperData--
const onSwiper = (swiper) => { navSwiper = swiper }
const initSwiper = (index) => {
  if (Number(areas.value.length) === 0) return false
  // --初始化--
  if (!navSwiper.el.querySelector('.bar')) {
    const newBar = document.createElement('div')
    newBar.setAttribute('class', 'bar')
    newBar.innerHTML = '<span class="xw-anim"></span>'
    navSwiper.wrapperEl.appendChild(newBar)
  }
  bar = navSwiper.el.querySelector('.bar')
  navSwiper.slides[navSwiper.activeIndex].querySelector('span').style.color = '#3388ff'
  // --Nav的可视宽度--
  clientWidth = navSwiper.wrapperEl.offsetWidth
  navWidth = 0
  for (let i = 0; i < navSwiper.slides.length; i++) {
    navWidth += navSwiper.slides[i].offsetWidth
  }
  // --点击slide事件--
  navSwiper.on('tap', () => {
    swiperMescroll(navSwiper.clickedIndex)
    // ----
    const newItems = []
    if (navSwiper.slides[navSwiper.clickedIndex].querySelector('span').innerText !== String(navText)) newItems.push(navSwiper.slides[navSwiper.clickedIndex].querySelector('span').innerText)
    proxy.$Myfun.setSearchRes(proxy, newItems, ['district'], (result) => { forSearch.value = result })
  })
  // ----
  setTimeout(() => { swiperMescroll(index) }, 100)
}
const swiperMescroll = (index) => {
  const clickIndex = index
  const clickSlide = navSwiper.slides[clickIndex]
  const activeSlidePosition = navSwiper.slides[clickIndex].offsetLeft

  // --释放时导航移动过渡--
  bar.style.transitionDuration = tSpeed + 'ms'
  bar.style.width = clickSlide.offsetWidth + 'px'
  bar.querySelector('span').style.width = clickSlide.querySelector('span').offsetWidth + 'px'
  bar.style.transform = 'translateX(' + activeSlidePosition + 'px)'

  // --导航居中--
  const navSlideWidth = clickSlide.offsetWidth
  // --activeSlide距左边的距离--
  const navActiveSlideLeft = navSwiper.slides[clickIndex].offsetLeft

  navSwiper.setTransition(tSpeed)
  if (navWidth > clientWidth) {
    if (navActiveSlideLeft < (clientWidth - navSlideWidth) / 2) {
      navSwiper.setTranslate(0)
    } else if (navActiveSlideLeft > navWidth - (navSlideWidth + clientWidth) / 2) {
      navSwiper.setTranslate(clientWidth - navWidth)
    } else {
      navSwiper.setTranslate((clientWidth - navSlideWidth) / 2 - navActiveSlideLeft)
    }
  }

  navSwiper.slides.forEach((current) => { current.querySelector('span').style.color = '#111111' })
  clickSlide.style.transitionDuration = tSpeed + 'ms'
  clickSlide.querySelector('span').style.color = '#3388ff'
}
// ----
const getTrueStyleAdvs = () => {
  if (proxy.$refs.forTrueWidthAdvs) {
    const imgEL = proxy.$refs.forTrueWidthAdvs
    const imgRatio = forFreeAdvs
    setTrueStyleAdvs.value = { height: `${Math.round(imgEL.offsetWidth / imgRatio)}px` }
  }
}
const getTrueStyle = () => {
  if (proxy.$refs.forTrueWidth) {
    const imgEL = proxy.$refs.forTrueWidth
    const imgRatio = forFree
    setTrueStyle.value = { height: `${Math.round(imgEL.offsetWidth / imgRatio)}px` }
  }
}
// ----
const setMarquee = () => {
  if (proxy.$refs.forMarquee) {
    const el = proxy.$refs.forMarquee.querySelector('ul')
    const forLi = el.innerHTML
    if (Number(el.firstChild.offsetWidth) > Number(el.offsetWidth)) {
      el.innerHTML = forLi + forLi
      showMarquee = setInterval(marqueefun, moveTime)
    }
  }
}
const marqueefun = () => {
  if (proxy.$refs.forMarquee) {
    const el = proxy.$refs.forMarquee.querySelector('ul')
    if (Number(el.lastChild.offsetWidth) <= Number(el.scrollLeft)) {
      el.scrollLeft = el.scrollLeft - el.firstChild.offsetWidth
    } else {
      el.scrollLeft = el.scrollLeft + 1
    }
  }
}
const stopRolling = () => {
  if (showMarquee) {
    clearInterval(showMarquee)
    showMarquee = null
  } else {
    showMarquee = setInterval(marqueefun, moveTime)
  }
}
// ----
const getCurrencyInfo = async (callback) => {
  // --获取系统设置无数据提示--
  const noDataItems = forSys.filter((item) => { return String(item.name) === 'market_noData' })
  if (Number(noDataItems.length) === 1) {
    proxy.$Myfun.getJsonData(noDataItems[0].value, (resJson) => {
      if (Array.isArray(resJson)) {
        resJson.some((item, index) => {
          if (String(item.id) === 'whereWe' && Number(item.desc.length) > 0) noData = proxy.$Myfun.setText(item.desc)
        })
      }
    })
  }
  // --获取数据--
  const funcData = forSys.filter((item) => { return String(item.name) === 'market_office' })
  if (Number(funcData.length) === 1) {
    const FData = funcData[0]
    proxy.$Myfun.getJsonData(FData.value, (resJson) => {
      const curRes = resJson[0]
      // ----
      if (curRes.remark && Number(curRes.remark.length) > 0) user.info = proxy.$Myfun.setText(curRes.remark)
      // ----
      user.title = proxy.$Myfun.setText(curRes.title)
      if (curRes.share_title) user.share_title = proxy.$Myfun.setText(curRes.share_title)
      if (curRes.share_desc) user.share_desc = proxy.$Myfun.setText(curRes.share_desc)
      if (curRes.share_img && Number(curRes.share_img.length) > 0) user.share_icon = curRes.share_img[0].image
    })
  }
  // ----
  if (user.info) nextTick(() => { setMarquee() })
  // --获取广告图片--
  const forImgData = {
    params: {
      'AdsSearch[type]': 7,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 10000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('ads/index', forImgData)
  ]).then(proxy.$Axios.spread((imgData) => {
    const advItems = []
    imgData.items.forEach((item) => {
      let forAdv = {}
      proxy.$Myfun.getJsonData(item.img_json, (resJson) => {
        forAdv = {
          id: item.id,
          image: resJson[0].image,
          link: item.link_url
        }
      })
      advItems.push(forAdv)
    })
    forAdvs.value = advItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
  // --设置微信分享功能--
  const forShare = {
    title: user.share_title,
    desc: user.share_desc,
    imgUrl: user.share_icon
  }
  setWebShare(forShare)
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  let forCity = ''
  if (myDistrict) {
    forCity = ',' + myProvince + ',' + myCity.value + ',' + myDistrict + ','
  } else if (myCity.value) {
    forCity = ',' + myProvince + ',' + myCity.value + ','
  } else if (myProvince) {
    forCity = ',' + myProvince + ','
  }
  // ----
  getListDataFromNet({
    forUrl: 'office/index',
    forData: {
      params: {
        'OfficeSearch[name]': infoSch.value,
        'OfficeSearch[city_json]': forCity || undefined,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    totalCount.value = res._meta.totalCount
    // ----
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forSex = ''
    if (Number(item.gender) > 0) forSex = (Number(item.gender) === 1) ? 'fa fa-user-tie-hair xw-color-12' : 'fa fa-user-tie-hair-long xw-color-5'
    // ----
    let forWechatImg = ''
    await proxy.$Myfun.getJsonData(item.wx_img, (resJson) => {
      if (Number(resJson.length) > 0) forWechatImg = resJson[0].image
    })
    // ----
    let forImg = ''
    const advItems = []
    await proxy.$Myfun.getJsonData(item.img_json, (resJson) => {
      if (Number(resJson.length) > 0) forImg = resJson[0].image
      // ----
      resJson.forEach((curItem) => {
        advItems.push({
          msrc: curItem.image,
          src: curItem.image,
          width: curItem.width,
          height: curItem.height,
          alt: ''
        })
      })
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      leader: proxy.$Myfun.setText(item.leader),
      sexIcon: forSex,
      telphone: item.telphone,
      wechat_img: forWechatImg,
      image: forImg,
      advs: advItems
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
  // ----
  getHeadFun(3)
}
// ----
const getHeadFun = (type, item) => {
  const self = this
  switch (Number(type)) {
    case 1: {
      if (item && Number(item.length) > 0) window.location.href = item
      break
    }
    case 2: {
      const options = {
        type: 1,
        forall: { show: true, text: '不限地区' },
        slideName: 'slideLeft',
        boxClass: 'SLB-box-left',
        itemName: myProvince || '',
        childName: myCity.value || '',
        title: '选择地区',
        list: myCityData,
        callback: (info) => { proxy.$Myfun.setSearchRes(proxy, info, ['province', 'city'], (result) => { forSearch.value = result }) }
      }
      proxy.$Myfun.isIndepth(sliding.value, 'open', options)
      break
    }
    case 3: {
      const newItems = []
      newItems.push(infoSch.value)
      proxy.$Myfun.setSearchRes(proxy, newItems, ['infoSch'], (result) => { forSearch.value = result })
      break
    }
  }
}
const getAuditFun = (type, item, event) => {
  switch (Number(type)) {
    case 1: {
      if (Number(item.advs.length) > 0) {
        const curEL = event.currentTarget
        const options = {
          actElement: curEL,
          addopt: {
            loop: true,
            dataSource: item.advs
          }
        }
        proxy.$Myfun.isIndepth(preImg.value, 'openPhotoSwipe', options)
      }
      break
    }
    case 2: {
      let options = {
        title: proxy.$Global.layer.titleTwo + item.telphone,
        content: proxy.$Global.layer.conEver,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnAsk,
          class: 'xw-color-24',
          callback: () => { window.location.href = 'tel:' + item.telphone }
        }]
      }
      if (item.wechat_img) {
        options = {
          title: proxy.$Global.layer.titleThree,
          content: '<div style="padding: 0 2.4rem;"><img src="' + item.wechat_img + '" style="width: 100%;"/></div>',
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: proxy.$Global.layer.btnAsk,
            class: 'xw-color-24',
            callback: () => { window.location.href = 'tel:' + item.telphone }
          }]
        }
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
    case 3: {
      window.location.href = 'tel:' + item.telphone
      break
    }
    case 4: {
      proxy.$Myfun.openPage(proxy, 'push', 'AddrMap', { dealer_id: item.id, fortable: 'office' })
      break
    }
  }
}

/* ---- */
watch(() => forSearch.value, (newVal, oldVal) => {
  infoSch.value = newVal.infoSch
  // ----
  curProv.value = newVal.province || '选择地区'
  // ----
  myProvince = newVal.province
  myCity.value = newVal.city
  myDistrict = newVal.district
  // ----
  if (String(newVal.province) !== String(oldVal.province) || String(newVal.city) !== String(oldVal.city)) {
    myDistrict = null
    myIndex = 0
    // ----
    proxy.$Myfun.setSearchRes(proxy, [myProvince, myCity.value], ['province', 'city', 'district'], (result) => { forSearch.value = result })
    // ----
    if (myProvince && myCity.value) {
      initData()
      nextTick(() => { initSwiper(myIndex) })
    }
  } else {
    // --重新请求数据--
    mescroll.scrollTo(0)
    mescroll.resetUpScroll()
  }
}, { deep: true })

/* ---- */
onBeforeMount(() => {
  infoSch.value = forSearch.value.infoSch
  // ----
  curProv.value = forSearch.value.province || '选择地区'
  // ----
  myProvince = forSearch.value.province
  myCity.value = forSearch.value.city
  myDistrict = forSearch.value.district
})
onMounted(() => {
  if (myProvince && myCity.value) {
    initData()
    nextTick(() => { initSwiper(myIndex) })
  }
  // ----
  setTimeout(() => { getTrueStyleAdvs() }, 100)
  // ----
  setTimeout(() => { getTrueStyle() }, 100)
  // ----
  getCurrencyInfo(() => {
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => {
  if (mescroll) mescroll.destroy()
  proxy.$Store.remove('forSearch')
})
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-bgCL-11 xw-flex xw-flex-align">
        <div class="TOP-msg xw-Lfg xw-flex-W1">
          <div class="forMarquee" v-if="user.info">
            <div ref="forMarquee" class="FMQ-con xw-act xw-flex xw-flex-align" @click="stopRolling">
              <ul class="xw-flex-W1">
                <li>{{user.info}}</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <!---->
      <div class="list-li-adv"><div ref="forTrueWidthAdvs"></div></div>
      <swiper :modules="modules" :autoplay="forAutoplay" :style="setTrueStyleAdvs" v-if="Number(forAdvs.length) > 0">
        <swiper-slide class="xw-act" v-for="(item, index) in forAdvs" @click="getHeadFun(1, item.link)"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.image + ')' }"></div></swiper-slide>
      </swiper>
      <!---->
      <div class="forTop xw-flex xw-flex-align">
        <a class="TOP-grap TOP-L xw-flex xw-flex-center" @click="getHeadFun(2)">
          <span><em class="fa fa-compass xw-color-12"></em>{{curProv}}</span>
        </a>
        <div class="TOP-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
          <em class="far fa-search TOP-L"></em>
          <p class="xw-flex-W1"><input class="schText" type="text" :placeholder="'业务处（共' + totalCount + '家）'" v-model.trim="infoSch"/></p>
          <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="infoSch"></em></transition>
          <span class="TOP-btn TOP-R xw-Lfg" @click="getHeadFun(3)">搜索</span>
        </div>
      </div>
      <div class="forNav xw-flex xw-flex-align" v-if="myCity">
        <span class="FNV-title FNV-L xw-Rfg">{{myCity}}</span>
        <div class="FNV-menu xw-flex-W1">
          <div class="FNV-box FNV-L FNV-R" v-if="Number(areas.length) > 0">
            <swiper :slides-per-view="'auto'" :freeMode="true" @swiper="onSwiper">
              <swiper-slide><span class="xw-middle">{{navText}}</span></swiper-slide>
              <swiper-slide v-for="(item, index) in areas"><span class="xw-middle">{{item.text}}</span></swiper-slide>
            </swiper>
          </div>
          <p class="xw-noData xw-middle" v-else >该地区无区县</p>
        </div>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-user xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items">
            <div class="LUR-title xw-act xw-ellipsis-2" @click="getAuditFun(1, item, $event)" v-if="item.name">{{item.name}}</div>
            <div class="LUR-img xw-act" :style="setTrueStyle" @click="getAuditFun(1, item, $event)" v-if="item.image"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.image + ')' }"></div></div>
            <div class="LUR-info xw-flex xw-flex-align">
              <div class="xw-flex-W1">
                <div class="LUR-leader xw-flex xw-flex-align" v-if="item.leader">
                  <span class="xw-color-20">主管：</span>
                  <div class="LUR-max xw-ellipsis">{{item.leader}}</div>
                  <em :class="item.sexIcon" v-if="item.sexIcon"></em>
                </div>
              </div>
              <a class="LUR-btn xw-Rfg" @click="getAuditFun(2, item)"><em class="fal fa-comments xw-color-1"></em></a>
              <a class="LUR-btn xw-Rfg" @click="getAuditFun(3, item)"><em class="fal fa-phone-volume xw-color-9"></em></a>
              <a class="LUR-btn" @click="getAuditFun(4, item)"><em class="fal fa-street-view xw-color-7"></em></a>
            </div>
          </li>
          <div class="list-li"><div ref="forTrueWidth"></div></div>
        </ul>
      </div>
    </div>
    <sliding-view ref="sliding"/>
    <preImg-view ref="preImg"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.forNav { margin-top: -0.8rem; height: 4rem; }
.FNV-menu { margin-left: 1rem; }
.FNV-menu .swiper { height: 100%; }

/* ---- */
.TOP-msg { padding: 0 0 0 0.4rem; }
.TOP-msg:before { top: 0.2rem; bottom: 0.2rem; width: 0.8rem; background: #ffffff; }

/* ---- */
.forMarquee { height: 100%; padding: 0 1rem; }
.FMQ-con { height: 100%; }
.FMQ-con ul { white-space: nowrap; overflow: hidden; }
.FMQ-con li { display: inline-block; font-size: 1.7rem; font-weight: bold; }

/* ---- */
.list-user li { position: relative; margin: 1rem 1rem 0; overflow: hidden; }
.list-user li:nth-of-type(1) { margin-top: 0; }
.LUR-title { padding: 1rem 1rem 0; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; }
.LUR-img { margin: 1rem 0 0; }
.LUR-info { padding: 1rem; }
.LUR-leader em { font-size: 1.6rem; margin-left: 0.5rem }
.LUR-max { max-width: 14rem; }
.LUR-btn { padding: 0 1.2rem; }
.LUR-btn em { font-size: 2rem; }
.LUR-btn:last-of-type { padding-right: 0; }
.list-li { margin: 0 1rem; }
</style>